package com.example.user.aspect;

import com.alibaba.fastjson.JSONObject;
import com.example.user.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;


/**
 * @ClassName WebLogAspect
 * @Deacription web日志切面
 * @Author test
 * @Date 2022/4/8
 * @Version 1.0
 **/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
    /**
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut("execution(public * com.example.user.controller..*.*(..))")
    public void webLog() {
    }

    private void initTid() {
        // 设置trace id
        String tid = MDC.get("Trance-ID");
        if (isEmpty(tid)) {
            MDC.put("Trance-ID", RandomStringUtils.randomAlphabetic(20));
        }
    }

    private void removeTid() {
        // 设置trace id
        String tid = MDC.get("Trance-ID");
        if (isNotEmpty(tid)) {
            MDC.remove("Trance-ID");
        }
    }

    /**
     * 环绕通知
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        initTid();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印请求 url
        log.info("Url:{}", request.getRequestURI());
        log.info("Parameters:{}", JsonUtil.toString(request.getParameterMap()));
        log.info("Class:{}", proceedingJoinPoint.getSignature().getDeclaringTypeName());
        log.info("Method:{}", proceedingJoinPoint.getSignature().getName());
        log.info("Request Args:{}", JSONObject.toJSONString(proceedingJoinPoint.getArgs()));
        //时间
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.info("Response:{}", JSONObject.toJSONString(result));
        // 执行耗时
        log.info("Time-Consuming:{} ms", System.currentTimeMillis() - startTime);
        removeTid();
        return result;
    }

    private String getBodyString(BufferedReader br) throws IOException {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        } finally {
            br.close();
        }
        return str;
    }
}
